package com.esayread.ui.history

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Book
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.esayread.data.ReadingHistory
import com.esayread.ui.theme.EsayReadTheme
import java.text.SimpleDateFormat
import java.util.*

@Composable
fun ReadingHistoryScreen(
    modifier: Modifier = Modifier,
    onHistoryClick: (ReadingHistory) -> Unit = {}
) {
    // 模拟阅读历史数据
    val sampleHistory = remember {
        listOf(
            ReadingHistory(
                bookId = "1",
                bookTitle = "三体",
                lastReadTime = System.currentTimeMillis() - 3600000, // 1小时前
                readingProgress = 0.65f,
                currentChapter = "第二章：三体文明",
                currentPosition = 1250
            ),
            ReadingHistory(
                bookId = "2",
                bookTitle = "活着",
                lastReadTime = System.currentTimeMillis() - 86400000, // 1天前
                readingProgress = 0.32f,
                currentChapter = "第一章：少年时代",
                currentPosition = 680
            ),
            ReadingHistory(
                bookId = "3",
                bookTitle = "百年孤独",
                lastReadTime = System.currentTimeMillis() - 172800000, // 2天前
                readingProgress = 0.78f,
                currentChapter = "第十五章：最后的奥雷里亚诺",
                currentPosition = 2340
            ),
            ReadingHistory(
                bookId = "4",
                bookTitle = "1984",
                lastReadTime = System.currentTimeMillis() - 259200000, // 3天前
                readingProgress = 0.45f,
                currentChapter = "第二部：第六章",
                currentPosition = 890
            ),
            ReadingHistory(
                bookId = "5",
                bookTitle = "红楼梦",
                lastReadTime = System.currentTimeMillis() - 432000000, // 5天前
                readingProgress = 0.23f,
                currentChapter = "第八回：比通灵金莺微露意",
                currentPosition = 1560
            )
        ).sortedByDescending { it.lastReadTime }
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "阅读历史",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            Text(
                text = "最近阅读",
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        if (sampleHistory.isEmpty()) {
            // 空状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Icon(
                        imageVector = Icons.Filled.Book,
                        contentDescription = null,
                        modifier = Modifier.size(64.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "还没有阅读记录",
                        fontSize = 16.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "开始阅读一本书吧！",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        } else {
            // 历史记录列表
            LazyColumn(
                verticalArrangement = Arrangement.spacedBy(12.dp),
                modifier = Modifier.fillMaxSize()
            ) {
                items(sampleHistory) { history ->
                    ReadingHistoryItem(
                        history = history,
                        onClick = { onHistoryClick(history) }
                    )
                }
            }
        }
    }
}

@Composable
fun ReadingHistoryItem(
    history: ReadingHistory,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onClick() },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 书籍封面占位符
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .clip(RoundedCornerShape(6.dp))
                    .background(MaterialTheme.colorScheme.surfaceVariant),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.Book,
                    contentDescription = "书籍封面",
                    modifier = Modifier.size(24.dp),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 书籍信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                // 书名
                Text(
                    text = history.bookTitle,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onSurface
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // 当前章节
                Text(
                    text = history.currentChapter,
                    fontSize = 14.sp,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 阅读进度
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    LinearProgressIndicator(
                        progress = { history.readingProgress },
                        modifier = Modifier
                            .weight(1f)
                            .height(4.dp),
                        color = MaterialTheme.colorScheme.primary,
                        trackColor = MaterialTheme.colorScheme.surfaceVariant,
                    )
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Text(
                        text = "${(history.readingProgress * 100).toInt()}%",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // 最后阅读时间
                Text(
                    text = formatLastReadTime(history.lastReadTime),
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

private fun formatLastReadTime(timestamp: Long): String {
    val now = System.currentTimeMillis()
    val diff = now - timestamp
    
    return when {
        diff < 3600000 -> "${diff / 60000}分钟前" // 小于1小时
        diff < 86400000 -> "${diff / 3600000}小时前" // 小于1天
        diff < 604800000 -> "${diff / 86400000}天前" // 小于1周
        else -> {
            val sdf = SimpleDateFormat("MM-dd", Locale.getDefault())
            sdf.format(Date(timestamp))
        }
    }
}

@Preview(showBackground = true)
@Composable
fun ReadingHistoryScreenPreview() {
    EsayReadTheme {
        ReadingHistoryScreen()
    }
}

@Preview(showBackground = true)
@Composable
fun ReadingHistoryItemPreview() {
    EsayReadTheme {
        ReadingHistoryItem(
            history = ReadingHistory(
                bookId = "1",
                bookTitle = "三体",
                lastReadTime = System.currentTimeMillis() - 3600000,
                readingProgress = 0.65f,
                currentChapter = "第二章：三体文明",
                currentPosition = 1250
            ),
            onClick = {}
        )
    }
}